
#include <Mfapi.h>
#include <Mfidl.h>
#include <mfreadwrite.h>  // for IMFSourceReader
#include <Mferror.h>

#include <stdio.h>

#include "audio_util.hpp"

void DumpAudioMediaType(IMFMediaType *media_type)
{
	GUID sub_type;
	if (media_type->GetGUID(MF_MT_SUBTYPE, &sub_type) == S_OK)
	{
		if (sub_type == MFAudioFormat_Float || sub_type == MFAudioFormat_PCM)
		{
            int is_float = (sub_type == MFAudioFormat_Float) ? 1 : 0;

			UINT32 channels = 0;
			media_type->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &channels);

			UINT32 samples_rate = 0;
			media_type->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &samples_rate);
            
			UINT32 sample_bits = 0;
			media_type->GetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, &sample_bits);

			UINT32 block_align = 0;
			media_type->GetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, &block_align);

			UINT32 avg_bytes_per_sec = 0;
			media_type->GetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, &avg_bytes_per_sec);
            
			UINT32 samples_indepent = 0;
			media_type->GetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, &samples_indepent);

			printf("Audio %s, channels: %u, samples_rate: %u, sample_bits: %u, block_align: %u, avg_bytes_per_sec: %u, samples_indepent: %u\n", 
                (is_float ? "Float" : "PCM"),
				channels, samples_rate, sample_bits, block_align, avg_bytes_per_sec, samples_indepent);
		}
		else if (sub_type == MFAudioFormat_AAC)
		{
			printf("Audio AAC\n");
		}
		else if (sub_type == MFAudioFormat_AMR_NB)
		{
			printf("Audio AMR_NB\n");
		}
		else if (sub_type == MFAudioFormat_AMR_WB)
		{
			printf("Audio AMR_WB\n");
		}
		else if (sub_type == MFAudioFormat_AMR_WP)
		{
			printf("Audio AMR_WP\n");
		}
		else
		{
			printf("Other Audio Data\n");
		}
	}
}

void EnumAllMediaTypes(IMFSourceReader *media_reader)
{
    printf("Enumerate all media format:\n");
	HRESULT hr;
    
    DWORD stream_index;
    for (stream_index = 0;; stream_index++)
    {
        DWORD type_index;
        for (type_index = 0;;type_index++)
        {
            IMFMediaType *media_type = NULL;
            hr = media_reader->GetNativeMediaType(stream_index, type_index, &media_type);
            if (hr != S_OK)
            {
                break;
            }
            printf("  ");
            DumpAudioMediaType(media_type);

            SafeRelease(media_type);
        }

        if (hr == MF_E_INVALIDSTREAMNUMBER) { break; }
    }

	return;
}
